#!/usr/bin/env python
# -*- coding:utf-8 _*-

from __future__ import print_function

import os
import sys
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
import matplotlib.pyplot as plt

analyPath = os.getcwd()
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = 10.5
dg = int(sys.argv[4]) if len(sys.argv) > 4 else 3

mark = ['.', ',', 'o', 'v', '^', '<', '>', '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_']
line = ['-', '--', '-.', ':']


class Train_CV_SGBRT(object):

    def __init__(self):
        self.data_path = analyPath + "/data"

    def analy(self, bench, mp, sp):

        # 读取数据
        data = pd.read_csv(os.path.join(self.data_path, bench + ".csv"))
        data = pd.DataFrame(data[[mp, sp, 'result']].values)

        # 定义线性模型
        Linear = LinearRegression()

        # 拟合主参数并做出预测
        sortsm = list(set(data[0]))
        sortsm.sort()

        # 拟合被影响参数并画图
        plt.figure(1, figsize=(6, 3), frameon=False)
        plt.figure(2, figsize=(6, 3), frameon=False)
        for i in range(len(sortsm)):
            # 拟合
            datatmp = data[data[0] == sortsm[i]]
            predictm = datatmp[2].mean(axis=0)
            sortss = list(set(datatmp[1]))
            sortss.sort()
            if min(sortss) != max(sortss):
                degree = min(len(sortss) - 1, dg)
                quadratic_featurizer = PolynomialFeatures(degree=degree)
                X = quadratic_featurizer.fit_transform(datatmp[[1]])
                Linear.fit(X, datatmp[2])
                # 画图
                # x = np.arange(sortss.min()[0], sortss.max()[0], (sortss.max()[0] - sortss.min()[0]) / 5).reshape(-1, 1)
                X = quadratic_featurizer.fit_transform([[x] for x in sortss])
                y = Linear.predict(X)
                label = mp + ' = ' + str(sortsm[i])
                plt.figure(1)
                plt.plot(sortss, y, label=label, marker=mark[i % len(mark)], linestyle=line[i % len(line)])
                plt.figure(2)
                plt.plot(sortss, y / predictm, label=label, marker=mark[i % len(mark)], linestyle=line[i % len(line)])

        plt.figure(1)
        plt.xlabel(sp)
        plt.legend(title=mp, bbox_to_anchor=(1.05, 1))
        plt.tight_layout()
        plt.savefig(analyPath + '/result/viewinteraction/' + bench + '-' + mp + '-' + sp + '-' + str(dg) + '-1.pdf')

        plt.figure(2)
        plt.xlabel(sp)
        plt.legend(title=mp, bbox_to_anchor=(1.05, 1))
        plt.tight_layout()
        plt.savefig(analyPath + '/result/viewinteraction/' + bench + '-' + mp + '-' + sp + '-' + str(dg) + '-2.pdf')


if __name__ == '__main__':
    train_cv_sgbrt = Train_CV_SGBRT()
    train_cv_sgbrt.__init__()
    train_cv_sgbrt.analy(sys.argv[1], sys.argv[2], sys.argv[3])
